package com.witmore.neutron.ai.web.wechat.client;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.jk.common.response.PageInfo;
import com.jk.common.response.ResponsePageResult;
import com.jk.common.response.ResponseResult;
import com.witmore.neutron.ai.web.wechat.client.dto.BatchStockAlertConfigRequest;
import com.witmore.neutron.ai.web.wechat.client.dto.QueryStockAlertConfigRequest;
import com.witmore.neutron.ai.web.wechat.client.dto.StockAlertConfigRequest;
import com.witmore.neutron.ai.web.wechat.dto.StockAlertConfigDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;

/**
 * MCP股票预警配置服务客户端
 * 负责调用MCP服务的股票预警配置接口
 *
 * @author 豆子高
 * @since 2025-01-27
 */
@Slf4j
@Component
public class McpStockAlertConfigClient {

    @Value("${spring.ai.mcp.stock-alert.service.base-url:http://localhost:8096}")
    private String mcpServiceBaseUrl;

    private final RestTemplate restTemplate;

    public McpStockAlertConfigClient() {
        this.restTemplate = new RestTemplate();
    }

    /**
     * 创建或更新单个股票预警配置
     */
    public ResponseResult<String> saveOrUpdateStockAlertConfig(Long userId, String stockCode, BigDecimal riseRatio,
                                                               BigDecimal fallRatio, Integer pushFrequency,Integer alertEnabled) {
        try {
            String url = mcpServiceBaseUrl + "/api/stock-alert-config/save-or-update";

            StockAlertConfigRequest request = new StockAlertConfigRequest();
            request.setUserId(userId);
            request.setStockCode(stockCode);
            request.setRiseRatio(riseRatio);
            request.setFallRatio(fallRatio);
            request.setPushFrequency(pushFrequency);
            request.setAlertEnabled(alertEnabled);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<StockAlertConfigRequest> entity = new HttpEntity<>(request, headers);

            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);

            if (response.getStatusCode() == HttpStatus.OK) {
                String responseBody = response.getBody();
                JSONObject jsonObject = JSONObject.parseObject(responseBody);
                if (Objects.requireNonNull(jsonObject).getInteger("code") == 200) {
                    return ResponseResult.success(jsonObject.getString("data"));
                }
                return ResponseResult.fail(500, "远程服务调用异常");

            } else {
                log.warn("MCP服务调用失败: statusCode={}", response.getStatusCode());
                return ResponseResult.fail(500, "远程服务调用异常");
            }

        } catch (Exception e) {
            log.error("调用MCP服务保存股票预警配置失败: userId={}, stockCode={}", userId, stockCode, e);
            return ResponseResult.fail(500, "远程服务调用异常");
        }
    }

    /**
     * 批量创建或更新股票预警配置
     */
    public ResponseResult<String> batchSaveOrUpdateAlertConfig(Long userId, String stockCodes, BigDecimal riseRatio,
                                                               BigDecimal fallRatio, Integer pushFrequency) {
        try {
            String url = mcpServiceBaseUrl + "/api/stock-alert-config/batch-save-or-update";

            BatchStockAlertConfigRequest request = new BatchStockAlertConfigRequest();
            request.setUserId(userId);
            request.setStockCodes(stockCodes);
            request.setRiseRatio(riseRatio);
            request.setFallRatio(fallRatio);
            request.setPushFrequency(pushFrequency);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<BatchStockAlertConfigRequest> entity = new HttpEntity<>(request, headers);

            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);

            if (response.getStatusCode() == HttpStatus.OK) {
                String responseBody = response.getBody();
                JSONObject jsonObject = JSONObject.parseObject(responseBody);
                if (Objects.requireNonNull(jsonObject).getInteger("code") == 200) {
                    return ResponseResult.success(jsonObject.getString("data"));
                }
                return ResponseResult.fail(500, "远程服务调用异常");
            } else {
                log.warn("MCP服务调用失败: statusCode={}", response.getStatusCode());
                return ResponseResult.fail(500, "远程服务调用异常");
            }

        } catch (Exception e) {
            log.error("调用MCP服务批量保存股票预警配置失败: userId={}, stockCodes={}", userId, stockCodes, e);
            return ResponseResult.fail(500, "远程服务调用异常");
        }
    }

    /**
     * 删除股票预警配置
     */
    public ResponseResult<String> deleteStockAlertConfig(Long userId, String stockCode) {
        try {
            String url = mcpServiceBaseUrl + "/api/stock-alert-config/delete?userId=" + userId + "&stockCode=" + stockCode;

            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.DELETE, null, String.class);

            if (response.getStatusCode() == HttpStatus.OK) {
                String responseBody = response.getBody();
                JSONObject jsonObject = JSONObject.parseObject(responseBody);
                if (Objects.requireNonNull(jsonObject).getInteger("code") == 200) {
                    return ResponseResult.success(jsonObject.getString("data"));
                }
                return ResponseResult.fail(500, "远程服务调用异常");

            } else {
                log.warn("MCP服务调用失败: statusCode={}", response.getStatusCode());
                return ResponseResult.fail(500, "远程服务调用异常");
            }

        } catch (Exception e) {
            log.error("调用MCP服务删除股票预警配置失败: userId={}, stockCode={}", userId, stockCode, e);
            return ResponseResult.fail(500, "远程服务调用异常");
        }
    }


    /**
     * 根据配置ID获取股票预警配置
     */
    public StockAlertConfigDTO getAlertConfigById(Long userId, Long configId) {
        try {
            String url = mcpServiceBaseUrl + "/api/stock-alert-config/get/" + configId + "?userId=" + userId;

            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);

            if (response.getStatusCode() == HttpStatus.OK) {
                String responseBody = response.getBody();
                JSONObject jsonObject = JSONObject.parseObject(responseBody);
                if (Objects.requireNonNull(jsonObject).getInteger("code") == 200) {
                    return JSONObject.parseObject(jsonObject.getString("data"), StockAlertConfigDTO.class);
                }
                return null;
            } else {
                log.warn("MCP服务调用失败: statusCode={}", response.getStatusCode());
                return null;
            }

        } catch (Exception e) {
            log.error("调用MCP服务获取股票预警配置失败: userId={}, configId={}", userId, configId, e);
            return null;
        }
    }

    /**
     * 分页查询股票预警配置
     */
    public ResponsePageResult<StockAlertConfigDTO> queryAlertConfigs(Long userId, String stockCode, String stockName,
                                                                     Integer alertEnabled, long page, long size) {
        try {
            String url = mcpServiceBaseUrl + "/api/stock-alert-config/query";

            QueryStockAlertConfigRequest request = new QueryStockAlertConfigRequest();
            request.setUserId(userId);
            request.setStockCode(stockCode);
            request.setStockName(stockName);
            request.setAlertEnabled(alertEnabled);
            request.setPage(page);
            request.setSize(size);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<QueryStockAlertConfigRequest> entity = new HttpEntity<>(request, headers);

            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);

            if (response.getStatusCode() == HttpStatus.OK) {
                // 直接解析ResponsePageResult，从data字段获取Page
                String responseBody = response.getBody();
                JSONObject jsonObject = JSONObject.parseObject(responseBody);
                if (Objects.requireNonNull(jsonObject).getInteger("code") == 200) {
                    List<StockAlertConfigDTO> records = JSONArray.parseArray(jsonObject.getString("records"), StockAlertConfigDTO.class);
                    PageInfo pageInfo = JSONObject.parseObject(jsonObject.getString("page"), PageInfo.class);
                    return ResponsePageResult.success(records, pageInfo);
                }
                return ResponsePageResult.fail(500, "远程服务调用异常");

            } else {
                log.warn("MCP服务调用失败: statusCode={}", response.getStatusCode());
                return ResponsePageResult.fail(500, "远程服务调用异常");
            }

        } catch (Exception e) {
            log.error("调用MCP服务分页查询股票预警配置失败: userId={}", userId, e);
            return ResponsePageResult.fail(500, "远程服务调用异常");
        }
    }

}
